package com.llap.exp190929.controller;

import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.dto.TransactionDto;
import com.llap.exp190929.entity.TransactionRecord;
import com.llap.exp190929.entity.User;
import com.llap.exp190929.error.BadRequestException;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.error.UnauthorizedException;
import com.llap.exp190929.service.TransactionRecordService;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("transactions")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class TransactionsController {
    private TransactionRecordService transactionRecordService;

    @GetMapping("")
    public PaginatedDto<TransactionRecord> findTransactionRecords(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam String cardNo,
            @RequestParam(required = false, defaultValue = "All") String filter,
            @RequestParam(required = false, defaultValue = "") String from,
            @RequestParam(required = false, defaultValue = "") String to) throws RestException {
        try {
            Date fromDate = null;
            Date toDate = null;
            if (!from.isEmpty() && !to.isEmpty()) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                fromDate = formatter.parse(from + " 00:00:00");
                toDate = formatter.parse(to + " 23:59:59");
            }
            return PaginatedDto.from(transactionRecordService.findTransactionRecords(page, pageSize, cardNo, filter, fromDate, toDate));
        }
        catch (Exception ex) {
            throw new BadRequestException(ex.getMessage());
        }
    }

    @GetMapping("{id}")
    public TransactionRecord findTransactionRecord(@PathVariable Integer id) {
        return transactionRecordService.findTransactionRecord(id).eraseCredential();
    }

    @PostMapping("")
    public TransactionRecord addTransactionRecord(@RequestBody TransactionDto dto) throws RestException {
        try {
            return transactionRecordService.addTransactionRecord(dto);
        }
        catch (Exception ex) {
            throw new BadRequestException(ex.getMessage());
        }
    }

}
